﻿using System;
using System.ComponentModel;
using System.Net;
using System.Net.Mail;
using EduFormManager.Properties;

namespace EduFormManager
{
    public static class EmailMessaging
    {
        private static SmtpClient m_client;
        private static string m_smtpHost;
        private static string m_port;
        private static string m_from;
        private static string m_to;
        private static MailMessage m_message;

        public class DeliveryMessageArgs : EventArgs
        {
            public String Caption { get; set; }
            public String Message { get; set; }
        }

        public static event EventHandler<DeliveryMessageArgs> Delivered;

        static EmailMessaging()
        {
            //m_smtpHost = Settings.Default.SmtpHost;
            //m_port = Settings.Default.Port;
            //m_client = new SmtpClient(m_smtpHost, int.Parse(m_port)) { EnableSsl = true };
            //m_client.Credentials = new NetworkCredential("emc.producer", "wonderful124578");
            //m_client.DeliveryMethod = SmtpDeliveryMethod.Network;
            //m_from = Settings.Default.EmailFrom;
            //m_to = Settings.Default.EmailTo;
            //m_message = new MailMessage(m_from, m_to);
            //if (Settings.Default.GUID == null)
            //{
            //    Settings.Default.GUID = Guid.NewGuid().ToString();
            //}

            //m_client.SendCompleted += m_client_SendCompleted;
        }

        static void m_client_SendCompleted(object sender, AsyncCompletedEventArgs e)
        {
            DeliveryMessageArgs args;
            if (e.Error == null)
            {
                args = new DeliveryMessageArgs() { Caption = "Информация", Message = "Сообщение успешно отправлено" };
            }
            else
            {
                args = new DeliveryMessageArgs() { Caption = "Ошибка", Message = e.Error.Message };
            }
            OnDelivered(sender, args);
        }

        public static void SendMessage(string subject, string body)
        {
            m_message.Body = body;
            m_message.Subject = subject;
            m_client.SendAsync(m_message, Settings.Default.GUID);
        }

        private static void OnDelivered(object sender, DeliveryMessageArgs args)
        {
            EventHandler<DeliveryMessageArgs> handler = Delivered;
            if (handler != null)
            {
                handler(sender, args);
            }
        }
    }
}
